<template>
  <view class="schedule-edit-container">
    <view class="page-header">
      <text class="page-title">编辑医生排班</text>
      <text class="page-subtitle">修改排班信息</text>
    </view>

    <view v-if="pageLoading" class="page-loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载数据中...</text>
    </view>

    <view v-else class="form-container">
      <view class="form-section">
        <text class="section-title">基本信息</text>
        
        <view class="form-item">
          <text class="form-label required">医生</text>
          <picker 
            mode="selector" 
            :range="doctorList" 
            range-key="label"
            :value="selectedDoctorIndex"
            @change="onDoctorChange"
          >
            <view class="picker-view">
              <text class="picker-text">{{ selectedDoctorName || '请选择医生' }}</text>
            </view>
          </picker>
          <text v-if="errors.doctor_id" class="error-text">{{ errors.doctor_id }}</text>
        </view>

        <view class="form-item">
          <text class="form-label required">排班日期</text>
          <picker mode="date" :value="formData.schedule_date" @change="onScheduleDateChange">
            <view class="picker-view">
              <text class="picker-text">{{ formData.schedule_date || '请选择排班日期' }}</text>
            </view>
          </picker>
          <text v-if="errors.schedule_date" class="error-text">{{ errors.schedule_date }}</text>
        </view>

        <view class="form-item">
          <text class="form-label required">开始时间</text>
          <picker mode="time" :value="formData.start_time" @change="onStartTimeChange">
            <view class="picker-view">
              <text class="picker-text">{{ formData.start_time || '请选择开始时间' }}</text>
            </view>
          </picker>
          <text v-if="errors.start_time" class="error-text">{{ errors.start_time }}</text>
        </view>

        <view class="form-item">
          <text class="form-label required">结束时间</text>
          <picker mode="time" :value="formData.end_time" @change="onEndTimeChange">
            <view class="picker-view">
              <text class="picker-text">{{ formData.end_time || '请选择结束时间' }}</text>
            </view>
          </picker>
          <text v-if="errors.end_time" class="error-text">{{ errors.end_time }}</text>
        </view>
      </view>

      <view class="form-section">
        <text class="section-title">号源配置</text>
        
        <view class="form-item">
          <text class="form-label required">时间段长度（分钟）</text>
          <uni-easyinput 
            v-model="formData.slot_duration_minutes"
            type="number"
            placeholder="每个号源的时长"
            :clearable="true"
            @input="calculateSlots"
          />
        </view>

        <view class="form-item">
          <text class="form-label required">总号源数</text>
          <uni-easyinput 
            v-model="formData.total_slots"
            type="number"
            placeholder="请输入总号源数"
            :clearable="true"
            @input="updateAvailableSlots"
          />
          <text v-if="errors.total_slots" class="error-text">{{ errors.total_slots }}</text>
          <text v-if="calculatedSlots > 0" class="form-hint">根据时间段计算：约{{ calculatedSlots}}个号源</text>
        </view>

        <view class="form-item">
          <text class="form-label">已预约号源</text>
          <view class="readonly-value">{{ formData.booked_slots }} 个</view>
        </view>

        <view class="form-item">
          <text class="form-label">可用号源</text>
          <view class="readonly-value highlight">{{ formData.available_slots }} 个</view>
        </view>
      </view>

      <view class="form-section">
        <text class="section-title">其他信息</text>
        
        <view class="form-item">
          <text class="form-label">备注</text>
          <textarea 
            v-model="formData.remark" 
            class="form-textarea" 
            placeholder="请输入备注信息（选填）"
            maxlength="200"
          />
        </view>

        <view class="form-item">
          <text class="form-label required">状态</text>
          <radio-group @change="onStatusChange" class="radio-group">
            <label class="radio-item">
              <radio value="1" :checked="parseInt(formData.status) === 1" color="#007aff"/>
              <text class="radio-text">正常</text>
            </label>
            <label class="radio-item">
              <radio value="2" :checked="parseInt(formData.status) === 2" color="#007aff"/>
              <text class="radio-text">停班</text>
            </label>
          </radio-group>
        </view>
      </view>

      <view class="form-actions">
        <button class="btn btn-cancel" @click="handleCancel">取消</button>
        <button class="btn btn-primary" @click="handleSubmit">保存</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'

const pageLoading = ref(true)
const scheduleId = ref('')

const formData = reactive({
  doctor_id: '',
  schedule_date: '',
  start_time: '',
  end_time: '',
  slot_duration_minutes: '',
  total_slots: '',
  booked_slots: 0,
  available_slots: 0,
  remark: '',
  status: 1
})

const errors = reactive({
  doctor_id: '',
  schedule_date: '',
  start_time: '',
  end_time: '',
  total_slots: ''
})

const calculatedSlots = ref(0)
const doctorList = ref([])
const selectedDoctorIndex = ref(-1)
const selectedDoctorName = ref('')

onMounted(async () => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  scheduleId.value = currentPage.options.id || ''
  
  if (!scheduleId.value) {
    uni.showToast({ title: '缺少排班ID', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/doctor_schedules/list' })
    }, 1500)
    return
  }
  
  // 先加载医生列表
  await loadDoctorList()
  
  // 再加载排班数据
  await loadScheduleData()
  
  pageLoading.value = false
})

async function loadDoctorList() {
  try {
    const dhSchedules = uniCloud.importObject('dh-doctor_schedules')
    const result = await dhSchedules.getDoctorList()
    
    if (result.code === 200 && result.data) {
      doctorList.value = result.data
    }
  } catch (err) {
    console.error('加载医生列表失败:', err)
    uni.showToast({ title: '加载医生列表失败', icon: 'none' })
  }
}

function onDoctorChange(e) {
  const index = e.detail.value
  selectedDoctorIndex.value = index
  
  if (index >= 0 && index < doctorList.value.length) {
    formData.doctor_id = doctorList.value[index].value
    selectedDoctorName.value = doctorList.value[index].label
    errors.doctor_id = ''
  }
}

async function loadScheduleData() {
  try {
    // 使用云函数获取排班详情
    const dhSchedules = uniCloud.importObject('dh-doctor_schedules')
    const result = await dhSchedules.getScheduleById(scheduleId.value)
    
    if (result.code === 200 && result.data) {
      const data = result.data
      Object.assign(formData, {
        doctor_id: data.doctor_id || '',
        schedule_date: data.schedule_date || '',
        start_time: data.start_time || '',
        end_time: data.end_time || '',
        slot_duration_minutes: data.slot_duration_minutes?.toString() || '',
        total_slots: data.total_slots?.toString() || '',
        booked_slots: data.booked_slots || 0,
        available_slots: data.available_slots || 0,
        remark: data.remark || '',
        status: data.status || 1
      })
      
      // 设置当前选中的医生
      if (data.doctor_id && doctorList.value.length > 0) {
        const index = doctorList.value.findIndex(doctor => doctor.value === data.doctor_id)
        if (index >= 0) {
          selectedDoctorIndex.value = index
          selectedDoctorName.value = doctorList.value[index].label
        }
      }
    } else {
      throw new Error(result.message || '排班不存在')
    }
  } catch (err) {
    console.error('加载排班数据失败:', err)
    uni.showToast({ title: err.message || '加载失败', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/doctor_schedules/list' })
    }, 1500)
  }
}

function onScheduleDateChange(e) {
  formData.schedule_date = e.detail.value
  errors.schedule_date = ''
}

function onStartTimeChange(e) {
  formData.start_time = e.detail.value
  errors.start_time = ''
  calculateSlots()
}

function onEndTimeChange(e) {
  formData.end_time = e.detail.value
  errors.end_time = ''
  calculateSlots()
}

function onStatusChange(e) {
  formData.status = parseInt(e.detail.value)
}

function calculateSlots() {
  if (formData.start_time && formData.end_time && formData.slot_duration_minutes) {
    const start = formData.start_time.split(':')
    const end = formData.end_time.split(':')
    const startMinutes = parseInt(start[0]) * 60 + parseInt(start[1])
    const endMinutes = parseInt(end[0]) * 60 + parseInt(end[1])
    const duration = parseInt(formData.slot_duration_minutes)
    
    if (endMinutes > startMinutes && duration > 0) {
      calculatedSlots.value = Math.floor((endMinutes - startMinutes) / duration)
    } else {
      calculatedSlots.value = 0
    }
  } else {
    calculatedSlots.value = 0
  }
}

function updateAvailableSlots() {
  const total = parseInt(formData.total_slots) || 0
  const booked = parseInt(formData.booked_slots) || 0
  formData.available_slots = Math.max(0, total - booked)
}

function validateForm() {
  let isValid = true
  
  if (!formData.doctor_id) {
    errors.doctor_id = '请选择医生'
    isValid = false
  } else {
    errors.doctor_id = ''
  }
  
  if (!formData.schedule_date) {
    errors.schedule_date = '请选择排班日期'
    isValid = false
  } else {
    errors.schedule_date = ''
  }
  
  if (!formData.start_time) {
    errors.start_time = '请选择开始时间'
    isValid = false
  } else {
    errors.start_time = ''
  }
  
  if (!formData.end_time) {
    errors.end_time = '请选择结束时间'
    isValid = false
  } else {
    errors.end_time = ''
  }
  
  if (!formData.total_slots || parseInt(formData.total_slots) <= 0) {
    errors.total_slots = '请输入有效的总号源数'
    isValid = false
  } else {
    errors.total_slots = ''
  }
  
  return isValid
}

async function handleSubmit() {
  if (!validateForm()) {
    uni.showToast({ title: '请检查表单错误', icon: 'none' })
    return
  }
  
  try {
    uni.showLoading({ title: '保存中...' })
    
    const totalSlots = parseInt(formData.total_slots) || 0
    const bookedSlots = parseInt(formData.booked_slots) || 0
    const submitData = {
      doctor_id: formData.doctor_id,
      schedule_date: formData.schedule_date,
      start_time: formData.start_time,
      end_time: formData.end_time,
      slot_duration_minutes: parseInt(formData.slot_duration_minutes) || 0,
      total_slots: totalSlots,
      booked_slots: bookedSlots,
      available_slots: Math.max(0, totalSlots - bookedSlots),
      status: formData.status,
      remark: formData.remark
    }
    
    const dhSchedules = uniCloud.importObject('dh-doctor_schedules')
    const result = await dhSchedules.updateSchedule(scheduleId.value, submitData)
    
    uni.hideLoading()
    
    if (result.code === 200) {
      uni.showToast({ title: '更新成功', icon: 'success' })
      setTimeout(() => {
        uni.redirectTo({ url: '/pages/business/doctor_schedules/list' })
      }, 1500)
    } else {
      uni.showToast({ title: result.message || '更新失败', icon: 'none' })
    }
  } catch (err) {
    console.error('更新失败:', err)
    uni.hideLoading()
    uni.showToast({ title: err.message || '更新失败', icon: 'none' })
  }
}

function handleCancel() {
  uni.redirectTo({ url: '/pages/business/doctor_schedules/list' })
}
</script>

<style lang="scss" scoped>
.schedule-edit-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 20rpx;
}

.page-header {
  background: #fff;
  padding: 40rpx;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.page-title {
  font-size: 44rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 12rpx;
}

.page-subtitle {
  font-size: 28rpx;
  color: #999;
  display: block;
}

.page-loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
  background: #fff;
  border-radius: 16rpx;
}

.loading-spinner {
  width: 80rpx;
  height: 80rpx;
  border: 6rpx solid #f3f3f3;
  border-top: 6rpx solid #007aff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 30rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

.form-container {
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;
}

.form-section {
  padding: 40rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 30rpx;
  padding-bottom: 16rpx;
  border-bottom: 2rpx solid #007aff;
}

.form-item {
  margin-bottom: 32rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  font-size: 28rpx;
  color: #666;
  display: block;
  margin-bottom: 16rpx;
  
  &.required::after {
    content: ' *';
    color: #ff3b30;
  }
}

.form-hint {
  font-size: 24rpx;
  color: #999;
  display: block;
  margin-top: 8rpx;
}

.readonly-value {
  padding: 20rpx;
  background: #f8f8f8;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #666;
  
  &.highlight {
    background: #e8f5e9;
    color: #2e7d32;
    font-weight: bold;
  }
}

.form-textarea {
  width: 100%;
  min-height: 160rpx;
  padding: 20rpx;
  font-size: 28rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  box-sizing: border-box;
  background: #fafafa;
}

.picker-view {
  padding: 20rpx;
  background: #fafafa;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
}

.picker-text {
  font-size: 28rpx;
  color: #333;
}

.radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 24rpx;
}

.radio-item {
  display: flex;
  align-items: center;
  padding: 16rpx 24rpx;
  background: #fafafa;
  border-radius: 8rpx;
  border: 1rpx solid #e0e0e0;
}

.radio-text {
  font-size: 28rpx;
  color: #333;
  margin-left: 12rpx;
}

.error-text {
  font-size: 24rpx;
  color: #ff3b30;
  display: block;
  margin-top: 8rpx;
}

.form-actions {
  display: flex;
  gap: 20rpx;
  padding: 30rpx 40rpx;
  background: #fff;
  border-top: 1rpx solid #f0f0f0;
}

.btn {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  font-size: 32rpx;
  border-radius: 12rpx;
  border: none;
  
  &.btn-cancel {
    background: #f5f5f5;
    color: #666;
  }
  
  &.btn-primary {
    background: #007aff;
    color: #fff;
  }
}
</style>
